import React, { useState, useEffect } from 'react';
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Radio,
  InputNumber,
  Select,
  Spin,
  Tabs,
  Divider,
  DatePicker,
  Checkbox,
  Row,
  Col,
} from 'antd';
import { upadataItemField, getDetail, addItemField, getDatatablelist } from '../api';
import { getTree, getSourcedataList } from '../../../SourceData/DataItem/api';
import { set } from 'lodash';
import DataFrame from './dataFrame';
import SetTime from './SetTime';
import styles from '../index.less';

const { Option } = Select;
const { TabPane } = Tabs;

const UpdateItem = props => {
  // 结构化数据
  const {
    visible,
    onCancel,
    onSuccess,
    data,
    type,
    catagolueid,
    dbsourceid,
    currentIndex = 0,
  } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [treeData, setTreeData] = useState([]); // 源数据库

  const [unitData, setUnitData] = useState([]); // 源数据库分类
  const [sourcedata, setSourcedata] = useState([]); // 源数据库表 列表

  // 详情
  const getDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    // setLoading(true);
    getDetail(paylaod).then(res => {
      setLoading(false);
      if (res.code === 0) {
        getUnitdata({ dataUnitId: res.data.unitid });
        getDatatablelistData({ sourceid: res.data.sourceid });
        form.setFieldsValue({ ...res.data });
      } else {
        // message.error(res.msg || '获取详情失败');
      }
    });
  };

  const getTreeData = () => {
    // setLoading(true);
    getTree().then(res => {
      setLoading(false);
      if (res.code === 0) {
        setTreeData(res.data);
      } else {
        // message.error(res.msg || '获取详情失败');
      }
    });
  };

  useEffect(() => {
    if (type === 'updata' && visible === true) {
      getDetailData();
    } else {
      form.resetFields();
    }
    if (visible) {
      getTreeData();
    }
    form.setFieldsValue({ tableState: '1' });
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);
    upadataItemField({ ...values, id: data.id }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   *
   * @param values
   */
  const addData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);

    addItemField({ ...values }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '添加失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      values.catagolueid = catagolueid;
      values.dbsourceid = dbsourceid;
      if (type === 'updata') updataData(values);
      if (type === 'add') addData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  /**
   * @zh-CN 获取数据源库
   * @param value
   */
  const getUnitdata = value => {
    setLoading(true);
    getSourcedataList(value).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setUnitData(res.data);
      } else {
        message.error(res.msg || '请求失败，请重试');
      }
    });
  };

  /**
   * @zh-CN 获取数据源库表名
   * @param value
   */
  const getDatatablelistData = value => {
    setLoading(true);
    getDatatablelist(value).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setSourcedata(res.data);
      } else {
        message.error(res.msg || '请求失败，请重试');
      }
    });
  };
  /**
   * @zh-CN 选择数据源库分类
   *
   * @param values
   */
  const selUnitidData = value => {
    const playlaod = { dataUnitId: value };
    form.setFieldsValue({ sourceid: null, tableName: null });
    getUnitdata(playlaod);
  };

  /**
   * @zh-CN 选择数据源库
   *
   * @param values
   */
  const selSourceData = value => {
    const playlaod = { sourceid: value };
    form.setFieldsValue({ tableName: null });
    getDatatablelistData(playlaod);
  };

  // 页签切换
  const tabChange = () => {};

  return (
    <>
      <Drawer
        getContainer={false}
        width={920}
        title={type === 'updata' ? '修改' : '添加'}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          <Tabs onChange={tabChange} type="card">
            <TabPane tab="基本信息" key="1">
              <Form {...formItemLayout} name="control-ref" form={form}>
                <Form.Item label="目标表名称" name="tableName" rules={[{ required: true }]}>
                  <Input maxLength={20} placeholder="请输入目标表名称" />
                </Form.Item>
                <Form.Item label="目标表类型" name="tabletype">
                  <Input maxLength={20} placeholder="请输入目标表类型" />
                </Form.Item>
                <Form.Item label="数据表备注" name="remarks">
                  <Input maxLength={20} placeholder="请输入数据表备注" />
                </Form.Item>

                <Form.Item name="sourceFrom" label="数据来源">
                  <Radio.Group>
                    <Radio value="0">基础表或视图</Radio>
                    <Radio value="1">Sql源</Radio>
                  </Radio.Group>
                </Form.Item>
                <Divider type="" style={{ marginBottom: 20 }} />
                <Form.Item label="源数据库分类" name="unitid" rules={[{ required: true }]}>
                  <Select placeholder="请选择源数据库分类" onChange={selUnitidData}>
                    {treeData.map(item => {
                      return (
                        <Option value={item.key} key={item.key}>
                          {item.title}
                        </Option>
                      );
                    })}
                  </Select>
                </Form.Item>
                <Form.Item label="源数据库" name="sourceid" rules={[{ required: true }]}>
                  <Select placeholder="请选择数据源库" onChange={selSourceData}>
                    {unitData.map(item => {
                      return (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      );
                    })}
                  </Select>
                </Form.Item>
                <Form.Item label="源数据库表名" name="sourceTable" rules={[{ required: true }]}>
                  <Select
                    placeholder="请选择数据源库表"
                    showSearch
                    filterOption={(input, option) =>
                      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {sourcedata.map(item => {
                      return (
                        <Option value={item.name} key={item.id}>
                          {item.name}
                        </Option>
                      );
                    })}
                  </Select>
                </Form.Item>

                <Form.Item label="源附加表" name="sourceJointable">
                  <Input.TextArea
                    maxLength={200}
                    allowClear
                    placeholder="请输入源附加表 最多200字符"
                  />
                </Form.Item>
                <Form.Item label="源表过滤条件" name="sourceWhere">
                  <Input maxLength={120} placeholder="请输入源表过滤条件" />
                </Form.Item>
                <Divider type="" style={{ marginBottom: 10 }} />
                <Form.Item label="源表主键字段" name="sourcePri">
                  <Input maxLength={120} placeholder="请输入源表主键字段" />
                </Form.Item>
                <Form.Item label="源表时间戳字段" name="sourceTimestamp">
                  <Input maxLength={120} placeholder="请输入源表时间戳字段" />
                </Form.Item>
                <Form.Item label="校准时间差(可负数)" name="correctime">
                  <InputNumber maxLength={120} style={{ width: 100 }} />
                </Form.Item>
                <Form.Item label="删除标记字段" name="sourceDelflag">
                  <Input maxLength={120} placeholder="请输入删除标记字段" />
                </Form.Item>
                <Form.Item label="多主键合成字段" name="sourceHcid">
                  <Input maxLength={120} placeholder="请输入删除标记字段" style={{ width: 200 }} />
                </Form.Item>
                <Form.Item label="OTHERCMD" name="othercmd">
                  <Input maxLength={120} placeholder="请输入OTHERCMD" style={{ width: 200 }} />
                </Form.Item>

                <Form.Item name="checkdataversion" label="数据版本检测">
                  <Radio.Group>
                    <Radio value="0">否</Radio>
                    <Radio value="1">是</Radio>
                  </Radio.Group>
                </Form.Item>

                <Form.Item label="数据传输时间戳" name="lasttimestamp">
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                </Form.Item>
                <Form.Item label="指纹排除字段" name="excludefield">
                  <Input maxLength={120} placeholder="请输入指纹排除字段" />
                </Form.Item>
                <Form.Item label="数据传输片长" name="pagelength">
                  <Input maxLength={120} placeholder="请输入数据传输片长" />
                </Form.Item>
                <Form.Item name="tableState" label="激活状态">
                  <Radio.Group>
                    <Radio value="0">禁用</Radio>
                    <Radio value="1">激活</Radio>
                  </Radio.Group>
                </Form.Item>
              </Form>
              <div style={{ textAlign: 'center' }}>
                <Button onClick={sendData} type="primary" loading={loading} disabled={loading}>
                  保存
                </Button>
              </div>
            </TabPane>
            <TabPane tab="数据结构" key="2">
              <DataFrame data={data} visible={visible} />
            </TabPane>
            <TabPane tab="任务执行时间" key="3">
              <SetTime data={data} visible={visible} />
            </TabPane>
          </Tabs>
        </Spin>
      </Drawer>
    </>
  );
};

export default UpdateItem;
